package com.example.shushiyunsst.fragment.main.mine.child

import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.album.Album
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.OnTextListener
import com.example.library_common.utils.upload_file.UploadFileWorker
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.IdentifyVerifyFragmentBinding
import com.example.shushiyunsst.fragment.getUserInfo
import com.example.shushiyunsst.util.IDENTIFY_VERIFY
import com.example.wallet.bean.UserInfo
import com.example.wallet.db.UserInfoManager

@Route(path = IDENTIFY_VERIFY)
class IdentifyVerifyFragment : BaseDataBindingFragment<IdentifyVerifyFragmentBinding>(),
    View.OnClickListener, OnTextListener {

    companion object {
        fun newInstance(): IdentifyVerifyFragment {
            val args = Bundle()
            val fragment = IdentifyVerifyFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var frontPicStr = ""

    private var oppositePicStr = ""

    private var handPicStr = ""

    private var identifyNameStr = ""

    private var identifyCodeStr = ""

    private var mUploadFileWorker: UploadFileWorker? = null

    override fun layoutId(): Int {
        return R.layout.identify_verify_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "实名认证"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this
        viewBinder.onTextListener = this

        val userInfoManager = UserInfoManager.userInfoManager
        val userInfoWrapper = userInfoManager.getUserInfoWrapper()
        val userInfo = userInfoWrapper?.userInfo

        if(userInfo?.checkStatusIdcard== UserInfo.checkedYes){
            loadData(userInfo)
        }
    }

    private fun loadData(userInfo: UserInfo) {

        viewBinder.verifyTv.visibility=View.GONE

        viewBinder.frontPicSelector.visibility= View.GONE
        viewBinder.frontPic.visibility = View.VISIBLE
        viewBinder.frontPic.isEnabled=false
        GlideApp.with(this)
            .load(userInfo.idFrontUrl)
            .into(viewBinder.frontPic)

        viewBinder.oppositePicSelector.visibility= View.GONE
        viewBinder.oppositePic.visibility = View.VISIBLE
        viewBinder.oppositePic.isEnabled=false
        GlideApp.with(this)
            .load(userInfo.idBackUrl)
            .into(viewBinder.oppositePic)

        viewBinder.handPicSelector.visibility= View.GONE
        viewBinder.handPic.visibility = View.VISIBLE
        viewBinder.handPic.isEnabled=false
        GlideApp.with(this)
            .load(userInfo.idFaceUrl)
            .into(viewBinder.handPic)

        viewBinder.identifyName.isEnabled=false
        viewBinder.identifyName.setText(userInfo.realName)

        viewBinder.identifyCode.isEnabled=false
        viewBinder.identifyCode.setText(userInfo.idcardNo)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.front_Pic_Selector,R.id.front_Pic -> {
                Album.getInstance()
                    .singleImage()
                    .onSuccess {
                        if (it.isNotEmpty()) {
                            v.visibility = View.GONE
                            viewBinder.frontPic.visibility = View.VISIBLE
                            frontPicStr = it[0].path
                            GlideApp.with(this)
                                .load(frontPicStr)

                                .into(viewBinder.frontPic)
                        }
                    }
                    .onFailed { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .execute(childFragmentManager)
            }
            R.id.opposite_Pic_Selector,R.id.opposite_Pic -> {
                Album.getInstance()
                    .singleImage()
                    .onSuccess {
                        if (it.isNotEmpty()) {
                            v.visibility = View.GONE
                            viewBinder.oppositePic.visibility = View.VISIBLE
                            oppositePicStr = it[0].path
                            GlideApp.with(this)
                                .load(oppositePicStr)
                                .into(viewBinder.oppositePic)
                        }
                    }
                    .onFailed { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .execute(childFragmentManager)
            }
            R.id.hand_Pic_Selector, R.id.hand_Pic -> {
                Album.getInstance()
                    .singleImage()
                    .onSuccess {
                        if (it.isNotEmpty()) {
                            v.visibility = View.GONE
                            viewBinder.handPic.visibility = View.VISIBLE
                            handPicStr = it[0].path
                            GlideApp.with(this)
                                .load(handPicStr)

                                .into(viewBinder.handPic)
                        }
                    }
                    .onFailed { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .execute(childFragmentManager)
            }
            R.id.verifyTv -> {
                if (checkInfo()) {
                    viewBinder.mProgressBar.visibility = View.VISIBLE
                    viewBinder.verifyTv.visibility = View.GONE

                    val mutableListOf = mutableListOf<String>()
                    mutableListOf.add(frontPicStr)
                    mutableListOf.add(oppositePicStr)
                    mutableListOf.add(handPicStr)
                    mUploadFileWorker = UploadFileWorker()
                    mUploadFileWorker?.setListener(object : UploadFileWorker.UpLoadOverListener {
                        override fun onUpLoadOver(res: List<String>) {
                            mUploadFileWorker = null
                            onSending(res)
                        }
                    })?.doWork(mutableListOf)
                }
            }
        }
    }

    private fun onSending(res: List<String>) {
        if (res.isEmpty() || res.size < 3) {
            Toast.makeText(_mActivity, "图片上传失败", Toast.LENGTH_SHORT).show()
            viewBinder.mProgressBar.visibility = View.GONE
            viewBinder.verifyTv.visibility = View.VISIBLE
            return
        }
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "idFrontUrl" to res[0],
            "idBackUrl" to res[1],
            "idFaceUrl" to res[2],
            "uid" to userInfo?.uid,
            "idCard" to identifyCodeStr,
            "realName" to identifyNameStr
        )
        RestClient.builder()
            .url(R.string.checkIdCard)
            .raw(JSON.toJSONString(maps))
            .raw(JSON.toJSONString(maps))
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
                getUserInfo(_mActivity)
            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
                viewBinder.verifyTv.visibility = View.VISIBLE
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
                viewBinder.verifyTv.visibility = View.VISIBLE
            }
            .build()
            .post()
    }

    private fun checkInfo(): Boolean {
        var flag = true

        if (identifyNameStr.isEmpty()) {
            flag = false
            Toast.makeText(_mActivity, "请输入真实姓名", Toast.LENGTH_SHORT).show()

        } else if (identifyCodeStr.isEmpty() || identifyCodeStr.length < 18) {
            flag = false
            Toast.makeText(_mActivity, "请输入正确身份证号", Toast.LENGTH_SHORT).show()
        } else if (handPicStr.isEmpty()) {
            flag = false
            Toast.makeText(_mActivity, "请选择手持身份证照片", Toast.LENGTH_SHORT).show()
        } else if (frontPicStr.isEmpty()) {
            flag = false
            Toast.makeText(_mActivity, "请选择正面照片", Toast.LENGTH_SHORT).show()
        } else if (oppositePicStr.isEmpty()) {
            flag = false
            Toast.makeText(_mActivity, "请选择反面照片", Toast.LENGTH_SHORT).show()
        }

        return flag
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.identifyName -> {
                identifyNameStr = s.toString()
            }
            R.id.identifyCode -> {
                identifyCodeStr = s.toString()
            }
        }
    }
}